package com.bike.service.impl;

import java.math.BigDecimal;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bike.entity.HhAgent;
import com.bike.entity.HhBusiness;
import com.bike.entity.HhBusinessRecord;
import com.bike.entity.HhBusinessUser;
import com.bike.entity.HhDining;
import com.bike.entity.HhFood;
import com.bike.entity.HhFoodTag;
import com.bike.entity.HhOpenUser;
import com.bike.entity.HhOrder;
import com.bike.entity.HhOrderFood;
import com.bike.entity.HhPayLog;
import com.bike.entity.HhPayRecord;
import com.bike.entity.HhServiceConfig;
import com.bike.mapper.HhAgentMapper;
import com.bike.mapper.HhBusinessMapper;
import com.bike.mapper.HhBusinessRecordMapper;
import com.bike.mapper.HhBusinessUserMapper;
import com.bike.mapper.HhDiningMapper;
import com.bike.mapper.HhFoodMapper;
import com.bike.mapper.HhFoodTagMapper;
import com.bike.mapper.HhOpenUserMapper;
import com.bike.mapper.HhOrderFoodMapper;
import com.bike.mapper.HhOrderMapper;
import com.bike.mapper.HhPayLogMapper;
import com.bike.mapper.HhPayRecordMapper;
import com.bike.util.Constant;
import com.bike.util.PageData;
import com.bike.util.TimeManager;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.thoughtworks.xstream.mapper.Mapper.Null;

@Service
public class HhOrderServiceImpl extends BaseServcieImpl  {

	@Autowired
	HhOrderMapper hhOrderMapper;
	@Autowired
	HhBusinessMapper hhBusinessMapper;
	@Autowired
	HhBusinessUserMapper hhBusinessUserMapper;
	@Autowired
	HhOrderFoodMapper hhOrderFoodMapper;
	@Autowired
	HhDiningMapper hhDiningMapper;
	@Autowired
	HhOpenUserMapper hhOpenUserMapper;
	@Autowired
	HhFoodMapper hhFoodMapper;
	@Autowired
	HhFoodTagMapper hhFoodTagMapper;
	@Autowired
	HhPayRecordMapper hhPayRecordMapper;
	@Autowired
	HhPayLogMapper hhPayLogMapper;
	@Autowired
    HhBusinessRecordMapper hhBusinessRecordMapper;
	@Autowired
	HhBusinessRecordServiceImpl hhBusinessRecordServiceImpl;
	@Autowired
	HhServiceConfigServiceImpl hhServiceConfigServiceImpl;
	@Autowired
	HhAgentMapper hhAgentMapper;
	@Autowired
	HhAgentServiceImpl hhAgentServiceImpl;
	
	/**
	* 保存
	*/
	public void saveOrUpdate(PageData pd, HhOrder record) {
		if(pd.getLong("orderId")>0){
			 //编辑
			hhOrderMapper.updateByPrimaryKeySelective(record);
		}else{
			hhOrderMapper.insertSelective(record);
		}
	}
	
	/**
	* 删除
	*/
	public int deleteHhOrderById(long orderId) {
		return hhOrderMapper.deleteByPrimaryKey(orderId);
	}
	
	/**
	*列表分页
	*/
	public PageData selectHhOrderList(PageData pd) {
		PageData result=new PageData();
		PageBounds pageBounds=(PageBounds) pd.get("pageB");
		if(pd.get("sort")==null||pd.get("order")==null){
			pd.put("sort", "add_time");
			pd.put("order", "desc");
		}
		List<HhOrder> records= hhOrderMapper.selectByPage(pd,pageBounds);
		result.put("rows",records );
		result.put("total", ((PageList<HhOrder>) records).getPaginator().getTotalCount());
		return result;
	}
	 
	/**
	*列表(全部)
	*/
	public List<HhOrder> listAll(PageData pd) {
		return  hhOrderMapper.selectAll(pd);
	}
	
	/**
	* 通过id获取数据
	*/
	public HhOrder selectByHhOrderId(Long orderId) {
		return hhOrderMapper.selectByPrimaryKey(orderId);
	}

	public HhOrder insertOrder(PageData pd, HhOpenUser user) throws Exception {
		PageData result=new PageData();
		 user=hhOpenUserMapper.selectByPrimaryKey(user.getOpenUserId());
		//桌字 
		HhDining dining=hhDiningMapper.selectByPrimaryKey(pd.getLong("diningId"));
		HhBusiness business=hhBusinessMapper.selectByPrimaryKey(dining.getBusinessId() );
		pd.put("businessId", dining.getBusinessId());
		
		HhOrder order=new HhOrder();
		int time=TimeManager.currentTime();
		order.setAddTime(time);
		order.setBusinessId(business.getBusinessId());
		order.setBusinessName(business.getName());
		order.setDiningId(dining.getDiningId());
		order.setUserId(user.getOpenUserId());
		order.setDiningName(dining.getName());
		String userName=user.getUserName();
		order.setUserName(userName);
		order.setOpenid(user.getOpenId());
		order.setNote(pd.getString("note"));
		order.setAgentId(business.getAgentId());
		hhOrderMapper.insertSelective(order);
		
		int totalCount=0;
		BigDecimal totalAmount=new BigDecimal("0");
		
		 String carFood=pd.getString("carFood");
		if(StringUtils.isEmpty(carFood)){
			return new HhOrder();
		}
		
		JSONArray  carFoodObj=JSONObject.parseArray(carFood);
		for(int i=0;i<carFoodObj.size();i++){
			JSONObject foodObj=carFoodObj.getJSONObject(i).getJSONObject("food");
			int quantity=foodObj.getIntValue("quantity");
			
			
			String [] foodIds=foodObj.getString("foodId").split("_");
			long foodId=Long.parseLong(foodIds[0]);
			long foodTagId=0;
			//商品
			HhFood food=hhFoodMapper.selectByPrimaryKey(foodId);
			HhOrderFood orderFood=new HhOrderFood();
			
			BigDecimal price=food.getPrice();
			
			 if(foodIds.length>1){
				 foodTagId=Long.parseLong(foodIds[1]);
				HhFoodTag foodTag= hhFoodTagMapper.selectByPrimaryKey(foodTagId);
				orderFood.setFoodTagId(foodTag.getFoodTagId());
				orderFood.setFoodTagName(foodTag.getName());
				price=foodTag.getPrice();
			 } 
			orderFood.setPrice(food.getPrice());
			orderFood.setName(food.getName());
			orderFood.setOrderId(order.getOrderId());
			orderFood.setAddTime(time);
			orderFood.setBusinessId(business.getBusinessId());
			orderFood.setBusinessName(business.getName());
			orderFood.setQuantity(quantity);
			orderFood.setUserId(user.getOpenUserId());
			orderFood.setFoodId(foodId);
			hhOrderFoodMapper.insertSelective(orderFood);
			
			//订单总数量  总价格
			totalCount+=quantity;
			totalAmount=totalAmount.add(new BigDecimal(String.valueOf(quantity)).multiply(price));
		}
		//更新订单金额
		HhOrder order2=new HhOrder();
		order2.setOrderId(order.getOrderId());
		order2.setTotalCount(totalCount);
		order2.setOrderPrice(totalAmount);//订单金额
		HhServiceConfig serviceConfig=hhServiceConfigServiceImpl.selectServciFee(order2,pd);
		//配送费
		order2.setSendFee(serviceConfig==null?new BigDecimal("0"):serviceConfig.getSendFee());
		//服务费     服务费=配送员分润+代理商分润+平台分润
		order2.setServicePrice(serviceConfig==null?new BigDecimal("0"):serviceConfig.getServiceFee());
		//代理商费
		order2.setAgentPrice(serviceConfig==null?new BigDecimal("0"):serviceConfig.getAgentFee() );
		//平台费
		order2.setPlatformPrice(serviceConfig==null?new BigDecimal("0"):serviceConfig.getPlatformFee() );
		
		BigDecimal withDrawFee=new BigDecimal("0");
		if(business.getPayWithdraw()==1){//顾客出提现手续费
			withDrawFee=totalAmount.add(order2.getServicePrice()).multiply(new BigDecimal(Constant.WXwithdrawFee));
			order2.setWithdrawPrice(withDrawFee);
		}
		//实付金额    
		order2.setTotalPrice(totalAmount.add(order2.getServicePrice()).add(withDrawFee));
		
		hhOrderMapper.updateByPrimaryKeySelective(order2);
		
		if(hhOpenUserMapper.updateOrderCount(user)<=0){
			throw new RuntimeException("重复下单");
		}
		
		order2.setOpenid(user.getOpenId());;
		order2.setBusinessId(business.getBusinessId());
		return order2;
	}

	public void updateOrderSuccess(PageData  pd, HhOrder order) {
		String aliOrder=pd.getString("trade_no");
		String wxOrder=pd.getString("transaction_id");
		String buyerId=pd.getString("buyer_id");
		HhOrder orderupdate=new HhOrder();
		orderupdate.setOrderId(order.getOrderId());
		orderupdate.setPayStatus(Constant.pay);
		orderupdate.setOrderStatus(Constant.orderStatusNosend);
		orderupdate.setPayWay(pd.getInteger("payway"));		
		if(orderupdate.getPayWay().intValue()==Constant.wxChannel){
			order.setUserName("微信用户");
		}else{
			order.setUserName("支付宝用户");
		}
		orderupdate.setUserName(order.getUserName());
		
		int result= hhOrderMapper.updateByPrimaryKeySelective(orderupdate);
		 //支付日志
		 HhPayLog payLog=new HhPayLog();
		 payLog.setAddTime(TimeManager.currentTime());
		 payLog.setAliOrder(aliOrder);
		 payLog.setFoodCount(order.getTotalCount());
		 payLog.setMoney(order.getTotalPrice());
		 payLog.setOrderId(order.getOrderId());
		 payLog.setUserId(order.getUserId());
		 payLog.setUserName(order.getUserName());
		 payLog.setNote(buyerId.equals("")?pd.getString("openid"):buyerId);
		 payLog.setWxOrder(wxOrder);
		 result+=hhPayLogMapper.insertSelective(payLog);
		 
		 
		 //商家余额 
		 HhBusiness business=hhBusinessMapper.selectByPrimaryKey(order.getBusinessId());
		 business.setBusinessId(order.getBusinessId());
		 //商家收入=用户支付的-代理费-平台费-配送费
		 logger.debug("---------------"+business.getBalance()+"--"+order.getTotalPrice()+"--"+order.getAgentPrice()+"--"+order.getPlatformPrice());
		 business.setBalance(business.getBalance().add(order.getTotalPrice()).subtract(order.getAgentPrice()).subtract(order.getPlatformPrice()).subtract(order.getSendFee()));
		 result+= hhBusinessMapper.updateBalance(business);
		 
		//平台增加平台费
		HhAgent plateForm=hhAgentServiceImpl.insertOrSelectByPrimaryKey();
		 if(business.getAgentId()==1){
			 if(order.getAgentPrice().doubleValue()>0){
				 plateForm.setBalance(plateForm.getBalance().add(order.getAgentPrice()));
				 hhAgentMapper.updateByPrimaryKeySelective(plateForm);
				//交易记录
				 HhPayRecord payRecord=new HhPayRecord();
				 payRecord.setAddTime(TimeManager.currentTime());
				 payRecord.setMoney(order.getAgentPrice());
				 payRecord.setOrderId(order.getOrderId());
				 payRecord.setUserId(order.getUserId());
				 payRecord.setUserName(order.getUserName());
				 payRecord.setToUserId(plateForm.getAgentId());
				 payRecord.setToUserName(plateForm.getName());
				 payRecord.setTransType(Constant.agentTransType);
				 payRecord.setType(Constant.platform);
				 payRecord.setNotes("下单服务费提成");
				 hhPayRecordMapper.insertSelective(payRecord);
			 }
		 }else{
			 if(order.getAgentPrice().doubleValue()>0){
				 //代理商增加代理商费
				 HhAgent agent=hhAgentMapper.selectByPrimaryKey(business.getAgentId());
				 agent.setBalance(agent.getBalance().add(order.getAgentPrice()));
				 hhAgentMapper.updateByPrimaryKeySelective(agent);
				 //交易记录
				 HhPayRecord payRecord=new HhPayRecord();
				 payRecord.setAddTime(TimeManager.currentTime());
				 payRecord.setMoney(order.getAgentPrice());
				 payRecord.setOrderId(order.getOrderId());
				 payRecord.setUserId(order.getUserId());
				 payRecord.setUserName(order.getUserName());
				 payRecord.setToUserId(agent.getAgentId());
				 payRecord.setToUserName(agent.getName());
				 payRecord.setTransType(Constant.agentTransType);
				 payRecord.setType(Constant.agentType);
				 payRecord.setNotes("下单服务费提成");
				 hhPayRecordMapper.insertSelective(payRecord);
			 }
		 }
		
		 //平台费
		 if(order.getPlatformPrice().doubleValue()>0){
			 plateForm.setBalance(plateForm.getBalance().add(order.getPlatformPrice()));
			 hhAgentMapper.updateByPrimaryKeySelective(plateForm);
			//交易记录
			 HhPayRecord payRecord=new HhPayRecord();
			 payRecord.setAddTime(TimeManager.currentTime());
			 payRecord.setMoney(order.getPlatformPrice());
			 payRecord.setOrderId(order.getOrderId());
			 payRecord.setUserId(order.getUserId());
			 payRecord.setUserName(order.getUserName());
			 payRecord.setToUserId(plateForm.getAgentId());
			 payRecord.setToUserName(plateForm.getName());
			 payRecord.setTransType(Constant.plateFormTransType);
			 payRecord.setType(Constant.platform);
			 payRecord.setNotes("下单服务费提成");
			 hhPayRecordMapper.insertSelective(payRecord);
		 }
		
		 //商家交易记录
		 result+= hhBusinessRecordServiceImpl.updateBusinessRocrd(pd,order);
		 
	}

	public List<HhOrder> selectByPd(PageData pd) {
		List<HhOrder> result= hhOrderMapper.selectByPage(pd);
		return result;
	}

	public int  updateOrderSendStatus(Long userId, Long orderId, Long sendUserId,Long businessId) {
		 HhOrder order=hhOrderMapper.selectByPrimaryKey(orderId);
		 //HhBusinessUser businessUser=hhBusinessUserMapper.selectByPrimaryKey(userId);
		 HhBusinessUser sendUser=hhBusinessUserMapper.selectByPrimaryKey(sendUserId);
		 
//		 if(order.getBusinessId()!=businessUser.getBusinessId()){
//			 return 0;
//		 }
		 
		 HhOrder record=new HhOrder();
		 record.setOrderId(orderId);
		 record.setOrderStatus(Constant.orderStatusSend);
		 record.setSendTime(TimeManager.currentTime());
		 record.setSendUserId(sendUser.getBusinessUserId());
		 record.setSendUserName(sendUser.getName());
		 
		 
		 
		
		 
		 HhBusiness business=hhBusinessMapper.selectByPrimaryKey(businessId);
		 if(order.getSendFee().doubleValue()>0){
			 if(sendUser.getRole().equals(Constant.boss)){
				 //更新商家余额
				 business.setBalance(business.getBalance().add(order.getSendFee()));
				 hhBusinessMapper.updateBalance(business);
				 
				 //交易记录
				 HhBusinessRecord businessRecord=new HhBusinessRecord();
				 businessRecord.setAddTime(TimeManager.currentTime());
				 businessRecord.setAmount(String.valueOf(order.getSendFee()));
				 businessRecord.setType(5);
				 businessRecord.setChannel("配送提成");
				 businessRecord.setFromId(business.getBusinessId());
				 businessRecord.setFromName(business.getName());
				 businessRecord.setToId(sendUser.getBusinessUserId());
				 businessRecord.setToName(sendUser.getName());
				 businessRecord.setBusinessId(order.getBusinessId());
				 businessRecord.setBusinessName(order.getBusinessName());
				 hhBusinessRecordMapper.insertSelective(businessRecord);
			 }else{ //服务员增加 配送费
				 sendUser.setBalance(sendUser.getBalance().add(order.getSendFee()));
				 hhBusinessUserMapper.updateByPrimaryKeySelective(sendUser);
				 //交易记录
				 HhPayRecord payRecord=new HhPayRecord();
				 payRecord.setAddTime(TimeManager.currentTime());
				 payRecord.setMoney(order.getSendFee());
				 payRecord.setOrderId(order.getOrderId());
				 payRecord.setUserId(business.getBusinessId());
				 payRecord.setUserName(business.getName());
				 payRecord.setToUserId(sendUser.getBusinessUserId());
				 payRecord.setToUserName(sendUser.getName());
				 payRecord.setTransType(Constant.sendTransType);
				 payRecord.setType(Constant.employPayRecordType);
				 hhPayRecordMapper.insertSelective(payRecord);
			 }
		 }
		 
	
		 return hhOrderMapper.updateByPrimaryKeySelective(record);
	}

	public List<HhOrderFood> selectOrderItemByOrderId(PageData pd) {
		return hhOrderFoodMapper.selectAll(pd);
	}

	public PageData selectHhOrderListAndItem(PageData pd) {
		PageData result=selectHhOrderList(pd);
		List<HhOrder> orders=(List<HhOrder>) result.get("rows");
		PageData param=new PageData();
		for(HhOrder order :orders){
			param.put("orderId", order.getOrderId());
			order.setChildren(hhOrderFoodMapper.selectAll(param));
		}
		return result;
	}

	public PageData updateOrderDelete(PageData pd) {
		PageData result=new PageData();
		
		HhOrder order=hhOrderMapper.selectByPrimaryKey(pd.getLong("orderId"));
		if(order.getUserId().longValue()==pd.getLong("userId")){
			HhOrder hhOrder=new HhOrder();
			hhOrder.setOrderId(order.getOrderId());
			hhOrder.setOrderStatus(Constant.orderStatusDelete);
			hhOrderMapper.updateByPrimaryKeySelective(hhOrder);
			result.put("msg", "成功");
		}else{
			result.put("msg", "订单只能本人删除");
		}
				
		return result;	
	}

	public PageData selectCountInfo(HhBusinessUser businessUser,PageData pd) {
		 
		int startTime=TimeManager.dateTime(pd.getString("startTime"));
		int endTime=TimeManager.dateTime(pd.getString("endTime"));
		
		pd.put("businessId", businessUser.getBusinessId());
		pd.put("startTimeInt", startTime);
		pd.put("endTimeInt", endTime);
		PageData orderAll= hhOrderMapper.selectCountOrderAll(pd);
		PageData orderSend =hhOrderMapper.selectCountOrderSend(pd);
		List<PageData> orderSaleRange =hhOrderMapper.selectOrderFoodSaleRange(pd);

		pd.put("orderCount", orderAll.getInteger("orderCount"));
		pd.put("totalPrice", orderAll.getDouble("totalPrice"));
		pd.put("sendCount", orderSend.getInteger("sendCount"));
		pd.put("sendFee", orderSend.getDouble("sendFee"));
		pd.put("saleFood", orderSaleRange);
		
		return pd;
	}

	public PageData selectCountForHome(PageData pd) {
		 // 总订单数量  总订单金额   微信支付  支付宝支付
		
		return hhOrderMapper.sleectCountForHome(pd);
	}
}

